package com.vben.common.core.util;

import com.vben.common.core.enums.ResponseCodeEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serial;
import java.io.Serializable;

/**
 * 响应信息主体
 *
 * @param <T>
 * @author sunnfun
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class R<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    private int code;

    private String message;

    private T data;

    public static <T> R<T> ok() {
        return restResult(null, ResponseCodeEnum.SUCCESS.getCode(), ResponseCodeEnum.SUCCESS.getMsg());
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, ResponseCodeEnum.SUCCESS.getCode(), ResponseCodeEnum.SUCCESS.getMsg());
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, ResponseCodeEnum.SUCCESS.getCode(), msg);
    }

    public static <T> R<T> failed() {
        return restResult(null, ResponseCodeEnum.FAIL.getCode(), ResponseCodeEnum.FAIL.getMsg());
    }

    public static <T> R<T> failed(String msg) {
        return restResult(null, ResponseCodeEnum.FAIL.getCode(), msg);
    }

    public static <T> R<T> failed(T data) {
        return restResult(data, ResponseCodeEnum.FAIL.getCode(), ResponseCodeEnum.FAIL.getMsg());
    }

    public static <T> R<T> failed(T data, String msg) {
        return restResult(data, ResponseCodeEnum.FAIL.getCode(), msg);
    }

    public static <T> R<T> failed(int code, String msg) {
        return restResult(null, code, msg);
    }

    public static boolean isOk(R<?> r) {
        return r.getCode() == ResponseCodeEnum.SUCCESS.getCode();
    }

    public static <T> R<T> restResult(T data, int code, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMessage(msg);
        return apiResult;
    }

}
